package test.top1.com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.utils.MyClickHouseUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.thrift.protocol.TMap;
import test.top1.com.atguigu.app.fun.DimAsyncFunction;
import test.top1.com.atguigu.bean.TradeSkuOrderBean;
import test.top1.com.atguigu.utils.DateFormatUtil;
import test.top1.com.atguigu.utils.MyKafkaUtil;
import test.top1.com.atguigu.utils.WindowFunctionUtil;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: Dws09_TradeSkuOrderWindow
 * Package: test.top1.com.atguigu.app.dws
 * Description:
 *
 * @Author ChenJun(有志男青年)
 * @Create 2023/5/10 8:47
 * @Version 1.0
 */
//数据流：web/app -> Mysql -> Maxwell -> Kafka(ODS) -> FlinkApp -> Kafka(DWD) -> FlinkApp -> Clickhouse(dws)
//程 序：Mock -> Mysql -> Maxwell -> Kafka(ZK) -> Dwd03_TradeOrderDetail -> Kafka(ZK) -> Dws09_TradeSkuOrderWindow(reids
// phoneix(hbase(zk hdfs))) -> Clickhouse(zk)
public class Dws09_TradeSkuOrderWindow {
    public static void main(String[] args) throws Exception {

        //TODO 1.获取运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // TODO 配置环境信息生产环境得有

//         env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                10, Time.of(1L, TimeUnit.DAYS), Time.of(3L, TimeUnit.MINUTES)
//        ));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
//        System.setProperty("HADOOP_USER_NAME", "atguigu");

        //TODO 2.从kafka 读取 读取 dwd层下单明细主题数据
        DataStreamSource<String> kafkaDS = env.fromSource(MyKafkaUtil.getKafkaSource("dwd_trade_order_detail",
                "sku_order_221109"), WatermarkStrategy.noWatermarks(), "kafka-source");

        //TODO 3.过滤空值 & 转换为json格式
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.flatMap(new RichFlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (value != null) {
                    out.collect(JSON.parseObject(value));
                }
            }
        });

        //TODO 4.提取时间生成watermark
        SingleOutputStreamOperator<JSONObject> jsonObjDSWithWMDS = jsonObjDS.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                return element.getLong("create_time");
            }
        }));

        //TODO 5.按照订单明细ID分组
        KeyedStream<JSONObject, String> keyedStreamDS = jsonObjDSWithWMDS.keyBy(json -> json.getString("id"));

        //TODO 6.去重,并转换为JavaBean对象
        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderBeanDS = keyedStreamDS.flatMap(new RichFlatMapFunction<JSONObject, TradeSkuOrderBean>() {

            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {

                StateTtlConfig ttlConfig = new StateTtlConfig.Builder(Time.milliseconds(5))
                        .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite)
                        .build();
                ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<String>("map-state", String.class);

                stateDescriptor.enableTimeToLive(ttlConfig);

                valueState = getRuntimeContext().getState(stateDescriptor);
            }

            @Override
            public void flatMap(JSONObject value, Collector<TradeSkuOrderBean> out) throws Exception {

                //获取状态值
                String state = valueState.value();

                if (state == null) {
                    valueState.update("1");

                    BigDecimal activityAmount = value.getBigDecimal("split_activity_amount");

                    out.collect(TradeSkuOrderBean.builder()
                            .skuId(value.getString("sku_id"))
                            .skuName(value.getString("sku_name"))
                            .originalAmount(value.getBigDecimal("split_original_amount"))
                            .orderAmount(value.getBigDecimal("split_total_amount"))
                            .activityAmount(activityAmount == null ? new BigDecimal("0.0") : activityAmount)
                            .couponAmount(value.getBigDecimal("split_coupon_amount"))
                            .build());
                }
            }
        });

        //TODO 7.开窗  聚合
        SingleOutputStreamOperator<TradeSkuOrderBean> resultDS = tradeSkuOrderBeanDS.windowAll(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10))).reduce(new ReduceFunction<TradeSkuOrderBean>() {
            @Override
            public TradeSkuOrderBean reduce(TradeSkuOrderBean value1, TradeSkuOrderBean value2) throws Exception {
                value1.setOriginalAmount(value1.getOriginalAmount().add(value2.getOriginalAmount()));
                value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                value1.setActivityAmount(value1.getActivityAmount().add(value2.getActivityAmount()));
                value1.setCouponAmount(value1.getCouponAmount().add(value2.getCouponAmount()));
                return value1;
            }
        }, new AllWindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, TimeWindow>() {
            @Override
            public void apply(TimeWindow window, Iterable<TradeSkuOrderBean> values, Collector<TradeSkuOrderBean> out) throws Exception {

//                TradeSkuOrderBean next = values.iterator().next();
//
//                next.setTs(System.currentTimeMillis());
//                next.setStt(DateFormatUtil.toYmdHms(window.getStart()));
//                next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
//
//                out.collect(next);
                WindowFunctionUtil.set(values,window,out);

            }
        });

        resultDS.print("-->");

        //TODO 8.关联维表补充维度信息

        //TODO 8.1 关联SKU  dim_sku_info
        SingleOutputStreamOperator<TradeSkuOrderBean> skuInfoDS = AsyncDataStream.unorderedWait(resultDS, new DimAsyncFunction<TradeSkuOrderBean>("DIM_SKU_INFO") {
            @Override
            public String getKey(TradeSkuOrderBean input) {
                return input.getSkuId();
            }

            @Override
            public void join(TradeSkuOrderBean input, JSONObject dimInfo) {
                input.setSpuId(dimInfo.getString("SPU_ID"));
                input.setTrademarkId(dimInfo.getString("TM_ID"));
                input.setCategory3Id(dimInfo.getString("CATEGORY3_ID"));
            }
        }, 60, TimeUnit.SECONDS);

        skuInfoDS.print("dimSkuInfoDS-->");

        //TODO 8.2 关联SPU  dim_sku_info
        SingleOutputStreamOperator<TradeSkuOrderBean> spuInfoDS = AsyncDataStream.unorderedWait(skuInfoDS,
                new DimAsyncFunction<TradeSkuOrderBean>("DIM_SPU_INFO") {
            @Override
            public String getKey(TradeSkuOrderBean input) {
                return input.getSpuId();
            }

            @Override
            public void join(TradeSkuOrderBean input, JSONObject dimInfo) {
                input.setSpuName(dimInfo.getString("SPU_NAME"));
            }
        }, 60, TimeUnit.SECONDS);

        //TODO 8.3 关联Trademark  dim_Trademark
        SingleOutputStreamOperator<TradeSkuOrderBean> trademarkInfoDS = AsyncDataStream.unorderedWait(spuInfoDS,
                new DimAsyncFunction<TradeSkuOrderBean>("DIM_BASE_TRADEMARK") {
                    @Override
                    public String getKey(TradeSkuOrderBean input) {
                        return input.getTrademarkId();
                    }

                    @Override
                    public void join(TradeSkuOrderBean input, JSONObject dimInfo) {
                        input.setTrademarkName(dimInfo.getString("TM_NAME"));
                    }
                }, 60, TimeUnit.SECONDS);

        //TODO 8.4 关联category3  dim_category3
        SingleOutputStreamOperator<TradeSkuOrderBean> category3InfoDS = AsyncDataStream.unorderedWait(trademarkInfoDS,
                new DimAsyncFunction<TradeSkuOrderBean>("DIM_BASE_CATEGORY3") {
                    @Override
                    public String getKey(TradeSkuOrderBean input) {
                        return input.getCategory3Id();
                    }

                    @Override
                    public void join(TradeSkuOrderBean input, JSONObject dimInfo) {
                        input.setCategory3Name(dimInfo.getString("NAME"));
                        input.setCategory2Id(dimInfo.getString("CATEGORY2_ID"));
                    }
                }, 60, TimeUnit.SECONDS);

        //TODO 8.5 关联category2  dim_category2
        SingleOutputStreamOperator<TradeSkuOrderBean> category2InfoDS = AsyncDataStream.unorderedWait(category3InfoDS,
                new DimAsyncFunction<TradeSkuOrderBean>("DIM_BASE_CATEGORY2") {
                    @Override
                    public String getKey(TradeSkuOrderBean input) {
                        return input.getCategory2Id();
                    }

                    @Override
                    public void join(TradeSkuOrderBean input, JSONObject dimInfo) {
                        input.setCategory2Name(dimInfo.getString("NAME"));
                        input.setCategory1Id(dimInfo.getString("CATEGORY1_ID"));
                    }
                }, 60, TimeUnit.SECONDS);

        //TODO 8.6 关联category1  dim_category1
        SingleOutputStreamOperator<TradeSkuOrderBean> category1InfoDS = AsyncDataStream.unorderedWait(category2InfoDS,
                new DimAsyncFunction<TradeSkuOrderBean>("DIM_BASE_CATEGORY1") {
                    @Override
                    public String getKey(TradeSkuOrderBean input) {
                        return input.getCategory1Id();
                    }

                    @Override
                    public void join(TradeSkuOrderBean input, JSONObject dimInfo) {
                        input.setCategory1Name(dimInfo.getString("NAME"));
                    }
                }, 60, TimeUnit.SECONDS);

        category1InfoDS.print("category1InfoDS--->");
        //TODO 9.写出数据
        category1InfoDS.addSink(MyClickHouseUtil.getSinkFunction("insert into dws_trade_sku_order_window values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));

        //TODO 10.启动任务
        env.execute("Dws09_TradeSkuOrderWindow");
    }
}
